#include "app_msg.h"

gate_status_t app_msg_json_2_msg(char *json, msg_t *msg)
{
    cJSON *root = cJSON_Parse(json);
    if (root == NULL)
    {
        log_error("json parse error");
        return GATE_ERROR;
    }

    msg->action = strdup(cJSON_GetObjectItem(root, "action")->valuestring);
    msg->connType = strdup(cJSON_GetObjectItem(root, "connType")->valuestring);
    msg->motorId = cJSON_GetObjectItem(root, "motorId")->valueint;

    cJSON *motorSpeedItem = cJSON_GetObjectItem(root, "motorSpeed");
    if (motorSpeedItem != NULL)
    {
        msg->motorSpeed = motorSpeedItem->valueint;
    }
    cJSON *statusItem = cJSON_GetObjectItem(root, "status");
    if (statusItem != NULL)
    {
        msg->status = strdup(statusItem->valuestring);
    }

    cJSON_Delete(root);
}

gate_status_t app_msg_msg_2_json(msg_t *msg, char *json)
{
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "action", msg->action);
    cJSON_AddStringToObject(root, "connType", msg->connType);
    cJSON_AddNumberToObject(root, "motorId", msg->motorId);

    if (msg->status != NULL)
    {
        cJSON_AddStringToObject(root, "status", msg->status);
    }
    cJSON_AddNumberToObject(root, "motorSpeed", msg->motorSpeed);

    char *out = cJSON_PrintUnformatted(root);
    strcpy(json, out);
    json[strlen(out)] = '\0';

    cJSON_Delete(root);

    return GATE_OK;
}

/*
设置电机速度:  写保持寄存器
    {
        "connType": "rs485",
        "motorId": 8,
        "action": "set",
        "motorSpeed": 200
    }
读取电机速度: 读取输入寄存器
    {
        "connType": "rs485",
        "motorId": 8,
        "action": "get"
    }

    返回json类型:
    {
        "connType": "rs485",
        "motorId": 8,
        "action": "get",
        "status": "ok"  // ok or error
        "motorSpeed": 200,
    }


*/
